import { buildUUID, buildUrl } from "@/common/uuid";
import { Message, TYPE } from "@/server/message";
export class SinalService {
    uid: string;
    socket: WebSocket;
    room: string;
    emit = new Map<TYPE|string, ((ev: Message) => any) | null>();
    constructor(sinalUrl: string, room: string) {
        this.uid = buildUUID();
        this.room = room;
        this.socket = new WebSocket(buildUrl(sinalUrl, room));
        this.socket.onopen = (e) => {
            console.log("open:", e);
            console.log("加入", buildUrl(sinalUrl, room));
            this.send0(Message.join(this.uid))
        }
        this.socket.onclose = (e) => {
            console.log("close:", e);
        }
        this.socket.onerror = (e) => {
            console.log("error:", e);
        }
        this.socket.onmessage = (msg) => {
            if (msg.data) {
                const data:Message = JSON.parse(msg.data)
                const call = this.emit.get(data.type);
                if (call) {
                    call(data);
                }
            }
        };

    }
    static joinRoom(sinalUrl: string, room: string) {
        const sinalService = new SinalService(sinalUrl, room)
        return sinalService;
    }

    leave(): void {
        this.socket.close();
    }
    offer(desc: any): void {
        if (desc) {
            this.send0(Message.offer(this.uid, desc));
        }
    }
    answer(desc: any): void {
        if (desc) {
            this.send0(Message.answer(this.uid, desc));
        }
    }
    //发送消息
    sendTo(type: any, data: any): void {
        if (data) {
            this.send0(Message.send(this.uid,type, data));
        }
    }
    message(call: ((this: WebSocket, ev: MessageEvent<any>) => any) | null) {
        if (this.socket) {
            this.socket.onmessage = call;
        }
    }

    on(emit: TYPE|string, call: ((ev: Message) => any) | null) {
        this.emit.set(emit, call);
    }
    private send0(message: Message): void {
        if (message && this.socket.OPEN == this.socket.readyState) {
            console.log("---发送消息---");
            this.socket.send(JSON.stringify(message));
        }
    }
}